#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 12345
#define BUFFER_SIZE 256

void *handle_client(void *socket_desc);

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    pthread_t thread_id;

    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    while ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))) {
        if (pthread_create(&thread_id, NULL, handle_client, (void*)&new_socket) != 0) {
            perror("could not create thread");
        }
        pthread_detach(thread_id); // Detach the thread so it cleans up after itself
    }

    if (new_socket < 0) {
        perror("accept failed");
        exit(EXIT_FAILURE);
    }

    return 0;
}

void *handle_client(void *socket_desc) {
    int sock = *(int*)socket_desc;
    char buffer[BUFFER_SIZE] = {0};
    char *response = NULL;

    // Read client message
    read(sock, buffer, BUFFER_SIZE);
    printf("Thread ID: %ld | Client: %s\n", pthread_self(), buffer);

    // Send a response
    response = "Who's there?";
    send(sock, response, strlen(response), 0);
    read(sock, buffer, BUFFER_SIZE); // Read next client message

    response = "knock knock who?";
    send(sock, response, strlen(response), 0);
    read(sock, buffer, BUFFER_SIZE); // Read final client message

    response = "Orange you glad I didn't say banana!";
    send(sock, response, strlen(response), 0);

    close(sock); // Close the socket
    return 0;
}

